package com.wy.business.manage.message.service;

import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.wy.business.manage.message.pojo.TManageCompanySession;
import com.wy.component.communication.HTTPClientUtils;
import com.wy.component.dataConvert.StringUtil;
import com.wy.component.properties.PropertiesUtil;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.services.AbstractBaseService;

/**
 * 
 * 项目名称：openportal_coding
 * 类名称：SessionService
 * 类描述：会话service
 * 创建人：黄忠
 * 创建时间：2016-4-20 下午12:07:05
 * 修改人：黄忠
 * 修改时间：2016-4-20 下午12:07:05
 * 版本信息：@version 1.0
 * Copyright (c) 2016万雍科技（上海）有限公司-版权所有  
 * 修改备注：
 * @version
 */
@Service
public class SessionService extends AbstractBaseService {
	
	@SuppressWarnings("unchecked")
	public boolean sendMsg(String userIds, String orgCodes, String msgContent) throws Exception  {
		
		//用户ID是否null  不为null 则表示部门发消息
		if(StringUtils.isEmpty(userIds) && StringUtils.isEmpty(orgCodes)) {
		 	throw new Exception("SessionService sendMsg 入参userids和部门codes同时为null."); 
		}
		//消息内容不能为null
		if(StringUtils.isEmpty(msgContent)) {
			throw new Exception("SessionService sendMsg 入参msgContent为null."); 
		}
		
		try {
			//redis里取登录人
			TSysUserinfo tSysUserinfo = loginUser();
			
			if(tSysUserinfo == null) {
				throw new Exception("SessionService SessionService 取得用户信息为null!");
			}
			String st = URLEncoder.encode(msgContent,"UTF-8");
			String title = URLEncoder.encode(tSysUserinfo.getUserName()+"的群聊","UTF-8");
			
			TManageCompanySession tManageCompanySession = new TManageCompanySession();
			
			//如果用户ID不为null 表示发人员消息 如果为null 表示发部门消息
			if(StringUtils.isNotEmpty(userIds)) {
				tManageCompanySession.setReceivercode(userIds);
				tManageCompanySession.setReceivertype("0");
				String[] userIdArr = userIds.split(",");
				//用户少于三个 则单聊 大于三个则群聊
				if(userIdArr.length < 3) {
					tManageCompanySession.setSessiontype("0");
					for (String string : userIdArr) {
						
			    		String url = new PropertiesUtil().getAppProperties("weChatInterfaceUrl") + "/weixinCmsSiteController.do?sendMsg&type=single"+
			    				"&id="+ string +"&sender=" + tSysUserinfo.getUserId() + "&content=" + st;
			    		HTTPClientUtils.sendGet(url);
			    		
					}
				} else { //群聊
					
					String userList = "[";
					for (int i = 0; i < userIdArr.length; i++) {
						
						if( i< userIdArr.length-1) {
							 userList = userList + "\"" + userIdArr[i]+"\",";
						}else {
							 userList = userList + "\"" + userIdArr[i]+"\"";
						}
					}
					tManageCompanySession.setSessiontype("1");
					userList = userList +",\"" + tSysUserinfo.getUserId() +  "\"]";
					//创建群聊
					String chatid=UUID.randomUUID().toString().replaceAll("-","");
					tManageCompanySession.setChatid(chatid);
					String url = new PropertiesUtil().getAppProperties("weChatInterfaceUrl") + "/weixinCmsSiteController.do?createChat&chatId="+ chatid +
							"&name="+ title +"&owner=" + tSysUserinfo.getUserId() + "&userList="+userList;
					HTTPClientUtils.sendGet(url);
					
					//群聊发送
					String urlSend = new PropertiesUtil().getAppProperties("weChatInterfaceUrl") + "/weixinCmsSiteController.do?sendMsg&type=group"+
							"&id="+ chatid +"&sender=" + tSysUserinfo.getUserId() + "&content="+st;
					HTTPClientUtils.sendGet(urlSend);
					
				}
				
			} else {
				//部门发消息
				
				String depIds=StringUtil.concatStrForSql(orgCodes);
				tManageCompanySession.setReceivercode(orgCodes);
				tManageCompanySession.setReceivertype("1");
				tManageCompanySession.setSessiontype("1");
				@SuppressWarnings("rawtypes")
				List<String> userInfoList = dataBaseDao.queryForListIn("T_SYS_USERINFO.queryUserByOrgIds", new ArrayList(), "AND T4.ORGCODE in (" + depIds +")");
				
				String userList = "[";
				for (int i = 0; i < userInfoList.size(); i++) {
					
					if( i< userInfoList.size()-1) {
						 userList = userList + "\"" + userInfoList.get(i)+"\",";
					}else {
						 userList = userList + "\"" + userInfoList.get(i)+"\"";
					}
				}
				userList = userList +"]";
				
				//创建群聊
				String chatid=UUID.randomUUID().toString().replaceAll("-","");
				String url = new PropertiesUtil().getAppProperties("weChatInterfaceUrl") + "/weixinCmsSiteController.do?createChat&chatId="+ chatid +
						"&name="+ title +"&owner=" + tSysUserinfo.getUserId() + "&userList="+userList;
				HTTPClientUtils.sendGet(url);
				
				//群聊发送
				String urlSend = new PropertiesUtil().getAppProperties("weChatInterfaceUrl") + "/weixinCmsSiteController.do?sendMsg&type=group"+
						"&id="+ chatid +"&sender=" + tSysUserinfo.getUserId() + "&content="+st;
				HTTPClientUtils.sendGet(urlSend);
			}
			
			tManageCompanySession.setIsavailable("1");
			tManageCompanySession.setMessagecontent(st);
			tManageCompanySession.setMessagetype("0");
			tManageCompanySession.setOperatoraccount(tSysUserinfo.getUserId());
			tManageCompanySession.setOperatorname(tSysUserinfo.getUserName());
			tManageCompanySession.setSender(tSysUserinfo.getUserId());
			tManageCompanySession.setSessionid(UUID.randomUUID().toString());
			tManageCompanySession.setUpdatetime(new Timestamp(new Date().getTime()));
			dataBaseDao.save(tManageCompanySession);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		
		
		
	}
	

}
